<?php

namespace app\portal\controller;

use cmf\controller\HomeBaseController;
use think\facade\Config;
use think\facade\Db;

// 自己的工具
class FieldController extends HomebaseController
{
	
	// 获取数据表字段
	/**
	 * 1、自己的模型的方法获取
	 * 2、模型获取
	 * 3、Db类获取
	 */
	
	// 请求地址 http://zhibo.com/portal/field/schema
	// 获取数据表字段信息（没有缓存）
	public function schema()
	{
		// 获取数据表字段类型（没有缓存）
		//$fields = \think\facade\Db::connect()->getTableFieldsInfo('tp6_admin_user');
		
		// 获取数据表字段（没有缓存）
		$fields = Db::connect()->getFields('tp6_admin_user');
		
		return $this->success($fields);
	}
	
	// 获取数据表的字段信息（用于模型，控制器获取数据，表单验证等）
	// http://www.zhibo.com/portal/field/fields
	public function fields()
	{
		$db_name = 'tp_miaodian';
		$table   = $this->getData('table','md_news','trim');
		$do_sql  = "SELECT `TABLE_NAME` tablename, `COLUMN_NAME` field,DATA_TYPE `type`,IS_NULLABLE is_null ,CHARACTER_MAXIMUM_LENGTH  `length`,NUMERIC_PRECISION num_length,NUMERIC_SCALE num_bit,COLUMN_COMMENT comment,COLUMN_DEFAULT `default` FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='".$db_name."' AND TABLE_NAME='".$table."' ";
		$fields  = Db::query($do_sql);
		$rule    = $get = [];
		
		$cline = chr(10).'<br/><br/>'.chr(10).chr(10);
		// 格式化
		//$fields = array_column($fields, null, 'field');
		$fields = array_column($fields, 'comment', 'field');
		$bangStr = '';
		foreach($fields as $field => $val){
			$bangStr      .= "'".$field."',";
			$rule[$field] = 'require';
			$get[$field]  = '$this->getData("'.$field.'", null,"trim")';
		}
		$result = ['msg' => var_export($fields, 1), 'rule' => $rule,];
		
		echo json_encode($fields, JSON_UNESCAPED_UNICODE);
		echo $cline;
		echo var_export($fields, 1);
		echo $cline;
		echo '['.$bangStr.']';
		echo $cline;
		echo var_export($get, 1);
		echo $cline;
		echo var_export($rule, 1);
		echo $cline;
		foreach($fields as $field => $val){
			echo '$'.$field.'=$this->getData("'.$field.'", null,"trim");'.chr(10);
		}
		echo $cline;
		//return $this->success($result);
	}
	
	// 所有的字段信息（用于apipost的描述参数）
	// http://www.zhibo.com/portal/field/all
	public function all()
	{
		$db_name = 'tp_live';
		$do_sql  = "SELECT `TABLE_NAME` tablename, `COLUMN_NAME` field,DATA_TYPE `type`,IS_NULLABLE is_null ,CHARACTER_MAXIMUM_LENGTH  `length`,NUMERIC_PRECISION num_length,NUMERIC_SCALE num_bit,COLUMN_COMMENT comment,COLUMN_DEFAULT `default` FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='".$db_name."'";
		$fields  = Db::query($do_sql);
		
		// 格式化
		//$fields = array_column($fields, null, 'field');
		$fields = array_column($fields, 'comment', 'field');
		
		echo json_encode($fields, JSON_UNESCAPED_UNICODE);
		
		//return $this->success($fields);
	}
	
}
